<template>
  <div class="user-management">
    <el-card class="login-form">
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" @click="handleAddUser">新增用户</el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.fullname" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 用户表格 -->
      <el-table :data="userList" border style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="userid" label="账号" width="120" />
        <el-table-column prop="fullname" label="用户名" width="120" />
        <el-table-column prop="role" label="角色" width="150">
          <template #default="scope">
            <el-tag :type="getRoleTagType(scope.row.role)">
              {{ scope.row.role }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑用户' : '新增用户'"
        width="30%"
    >
      <el-form :model="currentUser" label-width="100px" :rules="rules" ref="userForm">
        <el-form-item label="账号" prop="userid">
          <el-input v-model="currentUser.userid" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="用户名" prop="fullname">
          <el-input v-model="currentUser.fullname" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="currentUser.password" type="password" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="currentUser.role" placeholder="请选择角色">
            <el-option label="超级管理员" value="超级管理员" />
            <el-option label="县合管办领导" value="县合管办领导" />
            <el-option label="县合管办经办人" value="县合管办经办人" />
            <el-option label="乡镇农合经办人" value="乡镇农合经办人" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUser">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from 'axios';

// 定义接口基础URL
const baseURL = 'http://localhost:8080';

// 搜索表单数据
const searchForm = reactive({
  fullname: ''
});

// 表格数据
const userList = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);
const isEdit = ref(false);
const userForm = ref(null);

// 表单校验规则
const rules = {
  userid: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  fullname: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
};

const currentUser = ref({
  id: 0,
  userid: '',
  password: '',
  fullname: '',
  role: '县合管办经办人'
});

// 根据角色返回不同的标签类型
const getRoleTagType = (role) => {
  switch (role) {
    case "超级管理员":
      return "danger";
    case "县合管办领导":
      return "warning";
    case "县合管办经办人":
      return "primary";
    case "乡镇农合经办人":
      return "success";
    default:
      return "info";
  }
};

// 加载用户列表
const loadUserList = async () => {
  loading.value = true;
  try {
    const response = await axios.get(`${baseURL}/users/list`);
    if (response.data.code === 200) {
      userList.value = response.data.data;
    } else {
      ElMessage.error(response.data.message || '获取用户列表失败');
    }
  } catch (error) {
    ElMessage.error('获取用户列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索用户
const handleSearch = async () => {
  loading.value = true;
  try {
    const response = await axios.get(`${baseURL}/users/search`, {
      params: { fullname: searchForm.fullname }
    });
    if (response.data.code === 200) {
      userList.value = response.data.data;
    } else {
      ElMessage.error(response.data.message || '搜索失败');
    }
  } catch (error) {
    ElMessage.error('搜索失败');
  } finally {
    loading.value = false;
  }
};

// 重置搜索
const resetSearch = () => {
  searchForm.fullname = '';
  loadUserList();
};

// 处理添加用户
const handleAddUser = () => {
  isEdit.value = false;
  currentUser.value = {
    id: 0,
    userid: '',
    password: '',
    fullname: '',
    role: '县合管办经办人'
  };
  dialogVisible.value = true;
};

// 处理编辑用户
const handleEdit = (index, row) => {
  isEdit.value = true;
  currentUser.value = { ...row };
  dialogVisible.value = true;
};

// 处理删除用户
const handleDelete = async (index, row) => {
  try {
    await ElMessageBox.confirm('确认删除该用户吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const response = await axios.delete(`${baseURL}/users/delete/${row.id}`);
    if (response.data.code === 200) {
      ElMessage.success('删除成功');
      loadUserList();
    } else {
      ElMessage.error(response.data.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 提交用户信息
const submitUser = async () => {
  if (!userForm.value) return;
  
  try {
    await userForm.value.validate();
    
    const url = isEdit.value 
      ? `${baseURL}/users/update`
      : `${baseURL}/users/add`;
    
    const response = await axios[isEdit.value ? 'put' : 'post'](url, currentUser.value);
    
    if (response.data.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '添加成功');
      dialogVisible.value = false;
      loadUserList();
    } else {
      ElMessage.error(response.data.message || (isEdit.value ? '更新失败' : '添加失败'));
    }
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message);
    }
  }
};

// 初始化加载数据
onMounted(() => {
  loadUserList();
});
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-table {
  margin-top: 20px;
}

.el-tag {
  margin-right: 5px;
}
</style>